#include "app_msg.h"

/*
设置电机速度:
    {
        "connType": "rs485",
        "motorId": 8,
        "action": "set",
        "motorSpeed": 200
    }
读取电机速度:
    {
        "connType": "rs485",
        "motorId": 8,
        "action": "get"
    }

    返回json类型:
    {
        "connType": "rs485",
        "motorId": 8,
        "action": "get",
        "status": "ok"  // ok or error
        "motorSpeed": 200,
    }
*/

GateState_t App_Msg_Json2Char(msg_t *msg, char *json)
{
    cJSON *root = cJSON_Parse(json);
    if (root == NULL)
    {
        log_error("json解析失败");
        return GATE_ERROR;
    }
    //msg->connType = strdup(cJSON_GetObjectItem(root, "connType")->valuestring);
    msg->connType = strdup(cJSON_GetObjectItem(root, "connType")->valuestring);
    msg->action = strdup(cJSON_GetObjectItem(root, "action")->valuestring);
    msg->motorId = cJSON_GetObjectItem(root, "motorId")->valueint;
    if (cJSON_GetObjectItem(root, "motorSpeed") != NULL)
    {
        msg->motorSpeed = cJSON_GetObjectItem(root, "motorSpeed")->valueint;
    }
    if (cJSON_GetObjectItem(root, "status") != NULL)
    {
        msg->status = strdup(cJSON_GetObjectItem(root, "status")->valuestring);
    }

    cJSON_Delete(root);
    return GATE_OK;
}
GateState_t App_Msg_Char2Json(msg_t *msg, char *json)
{
    cJSON *root = cJSON_CreateObject();
    cJSON_AddStringToObject(root, "action", msg->action);
    cJSON_AddStringToObject(root, "connType", msg->connType);
    cJSON_AddNumberToObject(root, "motorId", msg->motorId);

    if (msg->status != NULL)
    {
        cJSON_AddStringToObject(root, "status", msg->status);
    }
    cJSON_AddNumberToObject(root, "motorSpeed", msg->motorSpeed);

    char *out = cJSON_PrintUnformatted(root);
    strcpy(json, out);
    json[strlen(out)] = '\0';

    cJSON_Delete(root);

    return GATE_OK;
}